<?php use_javascripts_for_form($form) ?>
<?php use_stylesheet('forms.css') //load css pf order page   ?>
<?php use_stylesheet('hoverTables.css') //load css of tables  ?>
<div id="form">  
    <!-- Back button -->
    <a href="<?php echo url_for('purchase/index') ?>" class="bt_back"><img src="<?php echo image_path('Buttons/bt_arrow_back.png') ?>" onmouseover="this.src='<?php echo image_path('Buttons/bt_arrow_back_hov.png') ?>'" onmouseout="this.src='<?php echo image_path('Buttons/bt_arrow_back.png') ?>'"></a>
    <?php
    //Session functions
    
    //Retrieve the hidden variables and put them in an array
    //Then put the array in the session
    function setVariables($id, $quantity){
        $array['id'] = $id;
        $array['number'] = $_POST['number']; 
        $array['amount'] = $quantity;
        $array['name'] = $_POST['name'];
        $array['type'] = $_POST['type'];
        $array['unit'] = $_POST['unit'];
        $array['stock'] = $_POST['stock'];
        $array['minstock'] = $_POST['minstock'];
        $array['supplier'] = $_POST['supplier'];
        $array['lastprice'] = $_POST['lastprice'];
        $array['ordered'] = $_POST['ordered'];

        $i = 0;
        while(isset($_SESSION['shoppinglist'][$i])){                  
            $i++;
        } 
        $_SESSION['shoppinglist'][$i] = $array;
        unset($_POST['add']);
    } 
    
    if(isset($_POST['empty_purchase'])){
        if(isset($_SESSION['shoppinglist'])){
            unset($_SESSION['shoppinglist']);
        }
    }
    if(isset($_POST['removep'])){
        $idline = $_POST['removep'];
        unset($_SESSION['shoppinglist'][$idline]);
    }            
    if(isset($_POST['addp'])) {
        $id = $_POST['id'];
        $quantity = $_POST['amount'];
        if($quantity == 0){ $quantity = 1; } else {$quantity = $_POST['amount'];}
         //check if part already exists in session
         //only add part when its not in session yet
        if(isset ($_SESSION['shoppinglist'])){
            $inlist = false;
            foreach($_SESSION['shoppinglist'] as $value){                 
                if($id == $value['id']){
                    $inlist = true;
                    break;
                }
            }
            if($inlist == false){
                setVariables($id, $quantity);
            }
        } else{
            setVariables($id, $quantity);
        }
        unset($_POST['add']);
    }
    if(isset($_POST['update'])){
        $i = 0;
        while(isset($_POST[''.$i.''])){
            $_SESSION['shoppinglist'][$i]['amount'] = $_POST['amount'.$i.''];
            $i++;
        }    
        unset($_POST['update']);
    }
    ?>  
    <!-- The actual form -->
    <form action="<?php echo url_for('purchase_show_list') ?>" method="post" target="_blank" <?php $form->isMultipart() and print 'enctype="multipart/form-data" ' ?>>
        <?php if (!$form->getObject()->isNew()): ?>
            <input type="hidden" name="sf_method" value="put" />
        <?php endif; ?>
        <fieldset>
            <legend class="bold">Materials</legend>
            <table class="table_top">
                <tr class="bold head_small">
                    <td width="65px">Material No.</td>
                    <td>Name</td>
                    <td>Type</td>
                    <td>Unit</td>
                    <td width="50px">Stock</td>
                    <td width="60px">Minimum</td>
                    <td width="50px">Ordered</td>
                    <td width="50px">Quantity</td>
                    <td width="120px">Supplier</td>
                    <td width="60px">Last price</td>
                    
                    <td width="45px"></td>
                </tr>
            </table>
            <div id="scroll_div" class="table_div">
                <table>
                    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" style="visibility:hidden;">
                       <input type="hidden" value="Add" name="retp"/>
                    </form>                   
                    <tr class="bold head_small" height="15px">
                        <td width="65px"></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td width="50px"></td>
                        <td width="60px"></td>
                        <td width="50px"></td>
                        <td width="50px"></td>
                        <td width="125px"></td>
                        <td width="60px"></td>
                        
                        <td width="20px"></td>
                    </tr>
                    <?php processList($needToPurchase, $form); ?>
                    <?php processList($materials, $form); ?>
                </table>
           </div>
        </fieldset>
        <?php if(!empty($_SESSION['shoppinglist'])){ //Check if the session has been set ?>
            <fieldset>
            <legend class="bold">Shopping List</legend>
            <div class="table_div">
                <table id="purchaselist">
                    <tr class="bold head_small">
                        <td>Material No.</td>
                        <td>Name</td>
                        <td>Type</td>
                        <td>Quantity</td>
                        <td>Unit</td>
                        <td>Supplier</td>
                        <td>Last Price</td>
                        
                        <td width="20px"></td>
                    </tr>
                    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
                        <input type="submit" name="empty_purchase" value="" class="bt_empty" title="Empty entire shoplist"/>
                    </form>
                    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
                        <input type="submit" name="update" value="" class="bt_update" title="Update shoplist"/>
                        <?php
                            foreach($_SESSION['shoppinglist'] as $value){ ?>                       
                                <tr class="table_hov <?php echo fmod($i, 2) ? 'even' : 'odd' ?> "><?php
                                echo '<td>'.$value['number'].'</td>';
                                echo '<td>'.$value['name'].'</td>';
                                echo '<td>'.$value['type'].'</td>';                               
                                echo '<td><input type="text" value="'.$value['amount'].'" name="amount'.array_search($value, $_SESSION['shoppinglist']).'" size="3"/></td>';
                                echo '<td>'.$value['unit'].'</td>';
                                $supplier = ContactTable::getInstance()->findOneBy('id', $value['supplier']);
                                if($supplier == null){
                                    echo '<td>'.$value['supplier'].'</td>';
                                }
                                else{
                                    echo '<td>'.$supplier->getName().'</td>';
                                }    
                                echo '<td>'.$value['lastprice'].'</td>';
                                echo '<input type="hidden" name="id" value="'.$value['id'].'"/>';
                                echo '<input type="hidden" name="name" value="'.$value['name'].'"/>';
                                echo '<input type="hidden" name="type" value="'.$value['type'].'"/>';
                                echo '<input type="hidden" name="unit" value="'.$value['unit'].'"/>';
                                echo '<input type="hidden" name="number" value="'.$value['number'].'"/>';
                                echo '<input type="hidden" name="stock" value="'.$value['stock'].'"/>';
                                echo '<input type="hidden" name="minstock" value="'.$value['minstock'].'"/>';
                                echo '<input type="hidden" name="ordered" value="'.$value['ordered'].'"/>';
                                echo '<input type="hidden" name="'.array_search($value, $_SESSION['shoppinglist']).'" value="'.array_search($value, $_SESSION['shoppinglist']).'"/>';
                                
                                echo '<td><input type="submit" value="'.array_search($value, $_SESSION['shoppinglist']).'" name="removep" class="bt_delete"/></td>';
                                echo '</tr>';
                            }
                        ?>
                    </form>  
                </table>
            </div>
            </fieldset>
            <div class="hidden_csrf"><?php echo $form['_csrf_token']->renderRow(); ?></div>
            <input type="submit" value="" class="print" title="Print shopping list"/>
        <?php } ?>
    </form>    
</div> 

<!-- Retrieve all the data of each material -->
<?php function processList($list, $form){ ?>
     <?php foreach ($list as $i=>$material): ?>
        <tr class="table_hov <?php echo fmod($i, 2) ? 'even' : 'odd' ?> ">
            <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
                <td><?php echo $material->getPartNumber() ?></td>
                <td><?php echo $material->getName() ?></td>
                <td><?php echo $material->getType() ?></td>
                <td><?php echo $material->getUnit() ?></td>
                <td><?php echo $material->getStock() ?></td>
                <td><?php echo $material->getMinStock() ?></td>
                <!-- Retrieve the total amount this material already has been ordered -->
                <?php $ordered = PurchaseTable::getAmountOrderedMaterial($material) ?>
                <td><?php foreach($ordered as $purchase){
                    if($purchase->getAmount() != null){
                        echo $purchase->getAmount();
                        $orderedAmount = $purchase->getAmount();

                    } else{ 
                        echo '0'; 
                        $orderedAmount = 0;
                    } 
               
                }?></td>
                <td><input type="text" name="amount" size="3" value="0"/></td>
                <!-- Retrieve all the suppliers from the contact table and show these in a drop down box -->
                <?php $suppliers = ContactTable::getInstance()->findBy('category_name', 'supplier') ?>
                <td>
                    <select name="supplier">
                        <option value="<?php echo null ?>"></option>
                        <?php foreach($suppliers as $supplier){ ?>
                            <option value="<?php echo $supplier->getId() ?>"><?php echo $supplier->getName() ?></option>
                        <?php } ?>
                    </select>
                </td>
                <!-- Retrieve the last price this material was bought for -->
                <?php $purchases = PurchaseTable::findLastPrice($material->getId()) ?>
                <td><?php 
                    if($purchases->count() == 0){ 
                        $lastprice = null; 
                    } else {
                        foreach($purchases as $purchase){
                            $lastprice = $purchase->getPrice();
                            echo $lastprice;
                            break;   
                        }    
                    } ?>
                </td>
                <!-- Put all the variables in hidden inputs so these that can be stored in the session -->
                <input type="hidden" name="id" value="<?php echo $material->getId() ?>"/>
                <input type="hidden" name="number" value="<?php echo $material->getPartNumber() ?>"/>
                <input type="hidden" name="name" value="<?php echo $material->getName() ?>"/>
                <input type="hidden" name="type" value="<?php echo $material->getType() ?>"/>
                <input type="hidden" name="unit" value="<?php echo $material->getUnit() ?>"/>
                <input type="hidden" name="stock" value="<?php echo $material->getStock() ?>"/>
                <input type="hidden" name="minstock" value="<?php echo $material->getMinStock() ?>"/>
                <input type="hidden" name="lastprice" value="<?php echo $lastprice ?>"/>
                <input type="hidden" name="ordered" value="<?php echo $orderedAmount ?>"/>
                <!-- The add material button -->
                <td><input type="submit" value="" name="addp" class="add_bt" title="Add to shoplist"/></td>
            </form>
        </tr>
<?php endforeach;
} ?>